$(document).ready(function()
    {
        $('.currency').formatCurrency();

        $.table_master = null;

        $.init_master = function()
        {
                $.ajax({
                url: base_url + 'br-02/barang/get_all',
                type: 'post',
                success : function(data)
                {
                    $.table_master = $('#barang_master').dataTable({
                        "bJQueryUI": true,
                        "sPaginationType": "full_numbers",
                        "aaData": data.data,
                        "bDestroy": true,
                        "aoColumns":[

                        {
                    'sTitle' : 'ID Barang',
                    'mDataProp' : 'ID_BARANG'
                },
                {
                    'sTitle' : 'Nama Barang',
                    'mDataProp' : 'NAMA_BARANG'
                },
                {
                    'sTitle' : 'Merk',
                    'mDataProp' : 'MERK'
                },
                {
                    'sTitle' : 'Harga',
                    'mDataProp' : 'HARGA_BELI'
                },
                {
                    'sTitle' : 'Nama Satuan',
                    'mDataProp' : 'NAMA_SATUAN'
                },
                {
                    'sTitle' : 'Stok Minimal',
                    'mDataProp' : 'STOK_MIN'
                },


                        ],
                        'fnServerData': function(sSource, aoData, fnCallback)
                {
                    $.ajax
                    ({
                        'dataType': 'json',
                        'type'    : 'POST',
                        'url'     : sSource,
                        'data'    : aoData,
                        'success' : fnCallback
                    });
                }
                    });
                },
                error: function(res)
                {
                    alert(res.responseText);
                },
                dataType: 'json'
            });
        }

        $.notif_order = function(data)
        {
            $("#barang_order_master tbody").html("");
            if(data.data != null)
            {
                var total = 0;
                for(var i = 0; i < data.data.length; i++)
                {
                    var newData = data.data[i];
                    total += newData.TOTAL_HARGA * 1;
                    $("#barang_order_master tbody").append('<tr>\n\
                        <td>'+newData.ID_BARANG+'</td>\n\
                        <td>'+newData.NAMA_BARANG+'</td>\n\
                        <td>'+newData.JUMLAH+'</td>\n\
                        <td class="currency">'+newData.TOTAL_HARGA / newData.JUMLAH+'</td>\n\
                        <td class="currency">'+newData.TOTAL_HARGA+'</td>\n\\n\
                        <td><a class="button button-gray no-text" href="#" style="width:25px;" onClick="$.delete_barang(\''+ newData.ID_DETAIL_ORDER +'\')"> <span id="delete_detail" class="bin"></span> </a></td>\n\
                    </tr>');
                    $('.currency').formatCurrency();
                }
                $("#barang_order_master tfoot").html('<tr>\n\
                        <th colspan="4">Total</th>\n\
                        <th class="currency">'+total+'</th>\n\
                        <th></th>\n\
                    </tr>');
                $('.currency').formatCurrency();
                $("#TOTAL").val(total);
            }
        }

        $.delete_barang = function(DETAIL_ORDER)
        {
            var yakin = confirm("Yakin hapus?");
            if (yakin){
                $.data_ajax('br-02/detail_order/delete_detail/' + DETAIL_ORDER, null, $.refresh_order_barang);
            }
        }

        $.refresh_order_barang = function()
        {
            $.data_ajax('br-02/detail_order/get_all/' + $("#ID_ORDER").val(), null, $.notif_order);
        }

        $.add_barang = function()
        {
            $.data_ajax('br-06/pembelian/add_order_brg/' + $("#ID_ORDER").val(), "#barang_form", $.refresh_order_barang);
            $('#dialog-barang-form').dialog('close');
        }

        

        $.list_order = function(data){
            $("#ID_ORDER").val(data.data)
        }

        $.update_barang = function()
        {
            if($("#FILTER_MODE_TOKO").attr('checked'))
                $.call_ajax('br-02/barang/update/' + selectID + "/" + $("#ID_TOKO").val(), "#barang_form", null);
            else
                $.call_ajax('br-02/barang/update/' + selectID, "#barang_form", null);
            $('#dialog-barang-form').dialog('close');
            $.init_master();
        }

        $('#dialog-barang-form').dialog({
            title: 'Data barang',
            width: '950px',
            autoOpen:false,
            modal:true,
            resizable:false
        });

        $('#dialog-suplier-form').dialog({
            title: 'Data barang',
            width: '950px',
            autoOpen:false,
            modal:true,
            resizable:false
        });

        $('#dialog-barang').dialog({
            title: 'Data barang',
            width: '950px',
            autoOpen:false,
            modal:true,
            resizable:false
        });

        $.resultbarang = function(data)
        {
            if($('td:first', data).html() != 'No matching records found')
            {
                $("#ID_BARANG").val($('td:first', data).html());
                $("#NAMA_BARANG").val($('td:eq(1)', data).html());
                $("#SATUAN").val($('td:eq(4)', data).html());
                $("#HARGA_BELI").val($('td:eq(3)', data).html());
            }
        }

        $('#barang_master tbody tr').live('click', function()
        {
            $.datatablebarangRowClicked(this);
        });

        $.datatablebarangRowClicked = function(that)
        {
            $.resultbarang(that);
            $('#dialog-barang').dialog('close');
        }

        $.add_barang_form = function()
        {
            $.clear_form("barang_form");
            $("#NO_ORDER").val($("#order_no").val());
            $("#add_submit").show();
            $("#update_submit").hide();
            $('#dialog-barang-form').dialog('open');
        }

        $("#barang_form").submit(function() {
            return false;
        });

        $("#order-pembelian").submit(function() {
            return false;
        });

        $('#ID_BARANG').click(function(){
            $('#dialog-barang').dialog('open');
        });
        
        $("#barang_add").click($.add_barang_form);
        $("#ID_BARANG").click($.add_barang_form);
        $("#add_barang").click($.add_barang);

        $.notif_order_real = function(data)
        {
            $("#barang_order_master tbody").html("");
            if(data.data != null)
            {
                var total = 0;
                
                for(var i = 0; i < data.data.length; i++)
                {
                    var newData = data.data[i];
                    total += newData.TOTAL_HARGA * 1;
                    $('.currency').formatCurrency();
                    $("#barang_order_master tbody").append('<tr>\n\
                        <td>'+newData.ID_BARANG+'</td>\n\
                        <td>'+newData.NAMA_BARANG+'</td>\n\
                        <td>'+newData.JUMLAH+'</td>\n\
                        <td class="currency">'+newData.TOTAL_HARGA / newData.JUMLAH+'</td>\n\
                        <td class="currency">'+newData.TOTAL_HARGA+'</td>\n\\n\
                        <td><span id="delete_detail" class="bin"></span></td>\n\
                    </tr>');
                }
                    $('.currency').formatCurrency();
                $("#barang_order_master tfoot").html('<tr>\n\
                        <th colspan="4">Total</th>\n\
                        <th class="currency">'+total+'</th>\n\
                        <th></th>\n\
                    </tr>');
                $('.currency').formatCurrency();
                $("#TOTAL").val(total);
            }
        }

        $.notif_add_order = function(data)
        {
            if(data.status == "OK")
            {
                $("#ID_ORDER").val(data.data);
                $("#delete_order").show();
                $("#barang_order_master").show();
                $("#barang_add").show();
                $("#update_order").show();
            }
            else
            if(data.status == "REALISASI")
            {
                if (confirm("Nomer PO sudah direalisasikan. Lanjutkan?")){
                    var current_order = data.data[0];
                    $("#ID_ORDER").val(current_order.ID_ORDER);
                    $("#NOMOR_ORDER").val(current_order.NOMOR_ORDER);
                    $("#SUPLIER").val(current_order.ID_SUPLIER);
                    $("#NAMASUPLIER").val(data.suplier);
                    $("#TGL_ORDER").val(current_order.TGL_ORDER);
                    //$("#DISKON").val(current_order.DISKON);
                    //$("#PPN").val(current_order.PPN);
                    $("#TOTAL").val(current_order.TOTAL);
                    $.data_ajax('br-02/detail_order/get_all/' + $("#ID_ORDER").val(), null, $.notif_order_real);

                    $("#delete_order").show();
                    $("#barang_order_master").show();
                    $("#barang_add").show();
                    $("#update_order").show();
                    $("#delete_order").attr("disabled","disabled");
                    $("#clear_order").attr("disabled","disabled");
                    $("#update_order").attr("disabled","disabled");
                    $("#barang_add").attr("disabled","disabled");

                    //$("#delete_detail").hide();
                    //$("#update_order").setAttribute("disabled", "disabled");

                    
                } else window.location = base_url + "br-06/pembelian/rencana/";
            }else
            {
                var current_order = data.data[0];
                $("#ID_ORDER").val(current_order.ID_ORDER);
                $("#NOMOR_ORDER").val(current_order.NOMOR_ORDER);
                $("#SUPLIER").val(current_order.ID_SUPLIER);
                $("#NAMASUPLIER").val(data.suplier);
                $("#TGL_ORDER").val(current_order.TGL_ORDER);
                $("#DISKON").val(current_order.DISKON);
                $("#PPN").val(current_order.PPN);
                $("#TOTAL").val(current_order.TOTAL);
                $.refresh_order_barang();

                $("#delete_order").show();
                $("#barang_order_master").show();
                $("#barang_add").show();
                $("#update_order").show();
            }
        }


        $("#add_order").click(function(){
            $("#add_order").hide();
            $("#cetak_order").show();
            $.data_ajax('br-06/pembelian/add_order', '#order-pembelian', $.notif_add_order);
        }
        );

        $("#cetak_order").click(function(){
            window.location = base_url + 'br-06/pembelian/cetakPO/'+$("#ID_ORDER").val()+'/';
            //$.call_ajax('br-06/pembelian/cetakPO/'+$("#ID_ORDER").val()+'/'+$("#NOMER_ORDER").val()+'/', null, null);
        }
        );
          
        $("#delete_order").click(function(){
            var sure = confirm("Yakin menghapus PO?");
            if (sure){
                $.data_ajax('br-06/pembelian/delete_order', '#order-pembelian', $.notif_delete);
            }else{
                
            }
        }
        );

        $.notif_delete = function(data)
        {
            if (data.status=='OKE'){
                alert("Data telah dihapus.");
                window.location = base_url + "br-06/pembelian/rencana/";
            }else alert("Data gagal dihapus.");
            
        }

        $.notif_update = function()
        {
            alert("Data telah tersimpan");
            window.location = base_url + "br-06/pembelian/rencana/";
        }

        $("#update_order").click(function(){
            $.data_ajax('br-02/order_barang/update/' + $("#ID_ORDER").val(), '#order-pembelian', $.notif_update);
        }
        );

        $.generate_no_order = function()
        {
            $.data_ajax('br-06/pembelian/genPO', null, $.genPO);   
        }
        
        $.genPO = function(data){
            var tgl = $("#TGL_ORDER").val();
            $id = data.data;
            if ($id<10) {
                $id = '000'+$id;
            }else if ($id<100) {
                $id = '00'+$id;
            }else if ($id<1000) {
                $id = '0'+$id;
            }
            $("#NOMER_ORDER").val($id + "-02/P/" + tgl);
        }

        $.calculate_total = function()
        {
            var unit = $("#UNIT").val();
            var harga = $("#HARGA_BELI").val();
            $("#HARGA").val(unit * harga);
        }

        $.calculate_all = function()
        {
            var total = $("#TOTAL").val();
            var diskon = $("#DISKON").val();
            var ppn = $("#PPN").val();

            diskon = (diskon <= 100) ? diskon * total : diskon;
            ppn = (ppn <= 100) ? ppn * total : ppn;

            $("#ALL_TOTAL").val(total - diskon + ppn *1);
        }

        $.init_master();
        $.generate_no_order();

        $("#TGL_ORDER").blur($.generate_no_order);
        $("#ID_TOKO").click($.generate_no_order);

        

        $("#UNIT").blur($.calculate_total);

        $("#DISKON").blur($.calculate_all);
        $("#PPN").blur($.calculate_all);
        
        $("#barang_order_master").hide();
        $("#barang_add").hide();
        $("#delete_order").hide();
        $("#update_order").hide();
        $("#cetak_order").hide();

    }
    );